package com.lemi.controller;

import com.lemi.dao.AttachmentMapper;
import com.lemi.dao.UserMapper;
import com.lemi.entity.Attachment;
import com.lemi.entity.User;
import com.lemi.util.BspResult;
import com.lemi.util.Constant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("home")
public class HomeController {

    @Resource
    private UserMapper userMapper;

    @Resource
    private AttachmentMapper attachmentMapper;

    /**
     * 跳转登陆页
     * @return
     */
    @RequestMapping("login")
    public String login(){
        return "login/login";
    }

    /**
     * 退出
     * @return
     */
    @RequestMapping("logout")
    public String logout(HttpSession session){
        session.removeAttribute(Constant.SESSION_USER_INFO);
        return "redirect:/home/login";
    }

    @RequestMapping("check")
    @ResponseBody
    public Object check(HttpSession session, User user) {
        System.out.println("这里是login/check");
        try {

            String userName = user.getUserName();
            String password = user.getPassword();
            if (StringUtils.isBlank(userName) || StringUtils.isBlank(password)) {
                return BspResult.err("账号或密码不能为空！");
            }

            Example e = new Example(User.class);
            e.createCriteria().andEqualTo("delFlag",false).andEqualTo("userName",userName)
                    .andEqualTo("password",password).andEqualTo("isUse",1);
            List<User> users = userMapper.selectByExample(e);
            if (users.isEmpty()) {
                return BspResult.err("账号或密码错误！");
            }

            User user1 = users.get(0);

            //头像
            Example ae = new Example(Attachment.class);
            ae.createCriteria().andEqualTo("delFlag",false).andEqualTo("businessId",user1.getId());
            List<Attachment> attachments = attachmentMapper.selectByExample(ae);
            if(attachments.size()>0){
                user1.setAttachment(attachments.get(0));
            }

            session.setAttribute(Constant.SESSION_USER_INFO, user1);
            session.setMaxInactiveInterval(3600);

            return BspResult.ok();
        }catch (Exception e){
            e.printStackTrace();
            return BspResult.err(Constant.SERVER_ERR);
        }
    }

    @RequestMapping("hello")
    public String hello(){
        System.out.println("HomeController hello...........");
        List<User> users = userMapper.selectAll();
        System.out.println(users.get(0));
        System.out.println(users.size());
        return "home";
    }
}
